﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;

//2013-07-08追加文本文件，记录文件打开的记录,用于侦错

namespace NNLInterface
{
    public partial class frmProcessCard : NNLInterface.frmBaseBasic
    {
         #region 初始化

        private string strDeptNo;
        string strTranNo = "";
        string strGroupNo = "";
        string DeptNo = "";
        string resCode = "";
        string strStartTime = "";
        string strEndTime = "";
        string ItemID;

       //报表数据源
        DataTable dtOrder;

        string strtxtFile = "";
    

        public frmProcessCard()  
        {
            InitializeComponent();
            this.SowCheckBox = true;
            this.CmdImport.Caption = "制程识别卡预览";
            this.CmdImport.ImageIndex = 22;

            this.CmdExcel.Caption = "产品信息报表";
            this.CmdExcel.ImageIndex = 22;
            this.ExcelButtonVisibility = true;

            this.PrintButtonVisibility = true;
            this.CmdPrint.Caption = "制程识别卡打印";

            this.lokDepart.EditValueChanged += new EventHandler(lokDepart_EditValueChanged);
            this.lokDepart.ProcessNewValue += new DevExpress.XtraEditors.Controls.ProcessNewValueEventHandler(lokDepart_ProcessNewValue);
            this.ListGrid.MouseDown += new MouseEventHandler(ListGrid_MouseDown);

        }

        void frmProcessCard_Load(object sender, EventArgs e)
        {
            IniDataSource();
        }


        private void IniDataSource()
        {
          

            lokPlanNo.Properties.ShowDropDown = DevExpress.XtraEditors.Controls.ShowDropDown.Never;
            lokDepart.Properties.ShowDropDown = DevExpress.XtraEditors.Controls.ShowDropDown.Never;


            //设定部门的数据源
            SetDeptDataSource();

            //显示订单数据
            string strSQL = "select   cast(0 as bit) as chkSelect ,  Code, ItemCode, dbo.GetShortDate( EST) est,"
                           + " dbo.GetShortDate( LET) let, Qty, dbo.GetShortDate(starttime) starttime,"
                           + " dbo.GetShortDate(endtime) endtime, Spec1Code,CustomerCode,1 as showTZ,"
                           + " Spec2Code,bb.PrintCount,cast('' as nvarchar(1000)) picPath,"
                           //2012-04-05显示订单的ChildCode字段中的第一个工序的资源代码
                           + " (SELECT DISTINCT oz.OperationMainResCode "
                           + " FROM OperationZ1 oz WHERE oz.TranNo=aa.TranNo AND   oz.ordercode=aa.Code "
                           + " and oz.procno=left(aa.childcode,2) ) Resource "
                           + " FROM OrdersOutZ1 aa "
                           + " left outer join ProcesCardPrintZ1 bb  on aa.code=bb.MoNo"
                           + " where 1=2 ";
            common.SubShowList(accessdb.GetRecord(strSQL).ADODataRst, this.ListGrid, this.ListView, false);
            common.subIniGrid(this.ListView, common.enumGridStyle.ViewStyle);
            this.ListView.Columns[0].OptionsColumn.AllowEdit = true;

            //设定显示图纸按钮控件
            DevExpress.XtraEditors.Repository.RepositoryItemButtonEdit repProLotNo = new DevExpress.XtraEditors.Repository.RepositoryItemButtonEdit();
            repProLotNo.Buttons[0].Kind = DevExpress.XtraEditors.Controls.ButtonPredefines.Glyph;
            repProLotNo.Buttons[0].Caption = "查看图纸";
            repProLotNo.TextEditStyle = DevExpress.XtraEditors.Controls.TextEditStyles.HideTextEditor;
            this.ListView.Columns["showTZ"].ColumnEdit = repProLotNo;
            this.ListView.Columns["showTZ"].Width = 100;
            repProLotNo.ButtonClick += new DevExpress.XtraEditors.Controls.ButtonPressedEventHandler(repProLotNo_ButtonClick);
            this.ListView.Columns["showTZ"].OptionsColumn.AllowMerge = DevExpress.Utils.DefaultBoolean.False;

            
            common.GetResourceString(this, this.Name.ToString());
            common.RestoreFormLayOut(this.Name, this.layOut, this.grpHead);
            common.ReStoreLayOut(this.ListView, this.Name.ToString());

            this.SetToolVisible(common.ToolVisible.ImportData);
            this.logButtonVisibility = false;



        }

        //打开文件
        void repProLotNo_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            //取得要打开的文件名
            //显示制品LotNo信息
            DataRow dt = ListView.GetFocusedDataRow();
            string strFileName = "";
            if (dt != null)
            {
                strFileName = dt["picpath"].ToString();
            }

            if (System.IO.File.Exists(strFileName))
            {
                System.Diagnostics.Process process = new System.Diagnostics.Process();
                process.StartInfo.FileName = strFileName;
                process.StartInfo.Verb = "Open";
                process.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Normal;
                process.Start();

            }
        }
        #endregion

        #region Grid选择按钮

        private void ListGrid_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
                DoShowMenu(this.ListView.CalcHitInfo(new Point(e.X, e.Y)));
        }

        void DoShowMenu(DevExpress.XtraGrid.Views.Grid.ViewInfo.GridHitInfo hi)
        {

            if (hi.HitTest == DevExpress.XtraGrid.Views.Grid.ViewInfo.GridHitTest.ColumnButton)
            {
                common.subSelectData(ListGrid, ListView);
            }
        }
        #endregion

        #region 控件变化事件


        private void SetDeptDataSource()
        {
            //如果是制5课计划，则部门直接是制5课的
            //string strSQL = "SELECT DepartNo,DeptName FROM vie_SysUserDepartMent vsudm WHERE vsudm.UserId='" + this.txtUser.Text + "'";
             //2012-03-27需要给出所有的课别，因需要将制1，制2课分开打印
            string strSQL = "SELECT bdm.DeptNo,bdm.DeptName FROM BasDepartMent bdm \n"
                           + "WHERE bdm.DeptNo<>'D009'";
            this.lokDepart.Properties.DataSource = accessdb.GetRecord(strSQL).ADODataRst;
           
        }


        void lokDepart_ProcessNewValue(object sender, DevExpress.XtraEditors.Controls.ProcessNewValueEventArgs e)
        {
           lookupeditProcess.LookUpEditProcessNewValue(sender, ref e);
            
        }

        void lokDepart_EditValueChanged(object sender, EventArgs e)
        {
            strDeptNo=this.lokDepart.Text;
            if (strDeptNo != "")
            {
                this.txtDepartName.Text = this.lokDepart.GetColumnValue("DeptName").ToString();
                
                //根据最终部门显示批次号
                if (strDeptNo == "Z2" || strDeptNo=="Z3")
                    strDeptNo = "Z1";

                //设定版本号
                string strSQL = "SELECT DISTINCT o.TranNo FROM Operation" + strDeptNo + " o ORDER BY o.TranNo desc";
                DataTable dt = accessdb.GetRecord(strSQL).ADODataRst;
                this.lokPlanNo.Properties.DataSource = dt;
                if (dt.Rows.Count >= 1)
                {
                    this.lokPlanNo.Text = dt.Rows[0][0].ToString();
                    this.lokPlanNo.EditValue = dt.Rows[0][0].ToString();
                }
            }
            else
            {
                this.txtDepartName.Text = "";
                this.lokPlanNo.Properties.DataSource = null;
            }
        }

        private void lokDepart_TextChanged(object sender, EventArgs e)
        {
            if (this.lokDepart.Text != "")
                this.txtDepartName.Text = this.lokDepart.GetColumnValue("DeptName").ToString();
            else
                this.txtDepartName.Text = "";
        }
        #endregion

        #region 工具栏按钮事件

        private void frmProcessCard_ToolButtonClick(object sender, string e)
        {
            try
            {
                switch (e)
                {
                    case "search":
                        if (!CheckData()) return;
                        SearchData();
                        break;
                    case "excel": //显示产品信息报表
                        showProInfReport();

                        //2013-08-02需要将选择的去掉
                        UncheckList();

                        break;
                    case "exit":
                        common.SaveFormLayOut(this.Name  , this.layOut, this.grpHead);
                        common.SaveLayout(this.ListView, this.Name .ToString());
                        this.Dispose();
                        break;
                        
                    case "import":  //显示制程识别卡报表
                        if(!subInsertData()) return;
                        //显示报表
                        ShowReport();

                        //2013-08-02需要将选择的去掉
                        UncheckList();
                        break;
                    case "print":
                        if (!subInsertData()) return;
                        //显示报表
                        PrintReport();

                        //2013-08-02需要将选择的去掉
                        UncheckList();
                        break;
                    default:
                        {
                            break;
                        }
                }


            }
            catch (Exception ex)
            {
                DevExpress.XtraEditors.XtraMessageBox.Show(ex.Message, common.sysParameter.MessageInf, MessageBoxButtons.OK, MessageBoxIcon.Information);
            }

        }

        private void UncheckList()
        {
            DataTable viewt = (DataTable)this.ListGrid.DataSource;
            for (int i = 0; i < viewt.Rows.Count; i++)
            {
                viewt.Rows[i]["chkSelect"] = 0;
            }
        }
        private void showProInfReport()
        {

            //pdm存储过程中需要的数据其中'NNL成品号',对应于APS料号中的前9位
            //'客户'对应客户字段
            //'货品规格'，对应于EPR中的spc字段
            //'图纸版本'对应BOM版本中的->后面的版本号
            //数据检测,如果没有数据,则提示后退出
            if (!common.CheckExistsData(this.ListView)) return ;
            this.ListView.CloseEditor();
            this.ListView.UpdateCurrentRow();
            DataTable viewt = (DataTable)this.ListGrid.DataSource;
            DataRow[] drs = viewt.Select("chkSelect=1");
            if (drs.Length < 1)
            {
                DevExpress.XtraEditors.XtraMessageBox.Show("请至少选择一笔数据!", common.sysParameter.MessageInf, MessageBoxButtons.OK, MessageBoxIcon.Information);
                return ;
            }

            //2013-07-09新建文本文件
            //如果文件夹不存在,则不需要建立
            //if(!System.IO.Directory.Exists(common.GetSolutionPath(Application.StartupPath) + "\\Log"))
            //{
            //    System.IO.Directory.CreateDirectory(common.GetSolutionPath(Application.StartupPath) + "\\Log");
            //}
            //string strFileName=System.DateTime.Now.ToString("yyyyMMdd HHmmss fff",System.Globalization.DateTimeFormatInfo.InvariantInfo);
            //strtxtFile = common.GetSolutionPath(Application.StartupPath) + "\\Log\\" + strFileName + ".txt";

            //FileStream tempStream = new FileStream(strtxtFile, FileMode.Create);
            //StreamWriter writer = new StreamWriter(tempStream);
            //string strLine = "";
            //writer.WriteLine(strLine);
            //writer.Close();
            //tempStream.Close();


            //生成主表数据
            DataTable dtMaster = new DataTable("dtMaster");
            dtMaster.Columns.Add("NNLFGNo", typeof(System.String)); //取NNL料号的前9位
            dtMaster.Columns.Add("CustCode", typeof(System.String)); //客户编号
            dtMaster.Columns.Add("PartDetail", typeof(System.String));  //客户成品号
            dtMaster.Columns.Add("DrawVersion", typeof(System.String)); //图纸编号，取APS的BOM版本号外的版本，如  v0001->1.0,则取1.0
            dtMaster.Columns.Add("MoNo", typeof(System.String)); //制令单号

            //2013-07-18加入工程师和审核人数据
            dtMaster.Columns.Add("Checker", typeof(System.String)); //审核人

            dtMaster.Columns.Add("Engineer", typeof(System.String)); //工程师


            //2013-06-25连接PDM服务器
            //string strpdmConnection = "server=" + common.sysParameter.PDMServerName
            //                          + ";uid=" + common.sysParameter.PDMUserName
            //                          + ";pwd=" + common.sysParameter.PDMPassWord
            //                          + ";database=" + common.sysParameter.PDMDataBaseName;

            string strpdmConnection = @"Data Source=" + common.sysParameter.PDMServerName 
                                      + ";Initial Catalog=" +  common.sysParameter.PDMDataBaseName
                                      + ";Persist Security Info=True;User ID=" + common.sysParameter.PDMUserName
                                      + ";Password=" + common.sysParameter.PDMPassWord;

            //以下为运行PDM的存储过程得到的9大类数据,需要保存在此9类明细表中
            //1.端子铆压(端子与电线或其他物料间的铆压)
            DataTable dtDetail1 = new DataTable("dtDetail1");
            dtDetail1 =(DataTable)accessdb.ExecuteSP(strpdmConnection, "sp_NNLFGNoDZDXMaoYaAPS",common.Choose.RetOneRecord, new object[]{"","","","","",""});

            //2.2.电线印字
            DataTable dtDetail2 = new DataTable("dtDetail2");
            dtDetail2.TableName = "dtDetail2";
            dtDetail2 = (DataTable)accessdb.ExecuteSP(strpdmConnection, "sp_NNLFGNoDXYinZhiaps", common.Choose.RetOneRecord, new object[] { "", "", "", "", "", "", "" });

            //3.半成品电测（电性测试）
            DataTable dtDetail3 = new DataTable("dtDetail3");
            dtDetail3 = (DataTable)accessdb.ExecuteSP(strpdmConnection, "sp_NNLFGNoDianCheAPS", common.Choose.RetOneRecord, new object[] { "", "", "", "", "", "", "" });

            //4.端子插拔
            DataTable dtDetail4 = new DataTable("dtDetail4");
            dtDetail4 = (DataTable)accessdb.ExecuteSP(strpdmConnection, "sp_NNLFGNoDZChaBaAPS", common.Choose.RetOneRecord, new object[] { "", "", "", "", "", "" });

            //5.IDC(刺破型端子铆压要求)
            DataTable dtDetail5 = new DataTable("dtDetail5");
            dtDetail5 = (DataTable)accessdb.ExecuteSP(strpdmConnection, "sp_NNLFGNoIDCAPS", common.Choose.RetOneRecord, new object[] { "", "", "", "", "", "" });


            //6.P架保持力(端子与P架)
            DataTable dtDetail6 = new DataTable("dtDetail6");
            dtDetail6 = (DataTable)accessdb.ExecuteSP(strpdmConnection, "sp_NNLFGNoDZPJia_BaoChiLiAPS", common.Choose.RetOneRecord, new object[] { "", "", "", "", "", "","" });

            //7.束带(束带绷张力)
            DataTable dtDetail7 = new DataTable("dtDetail7");
            dtDetail7 = (DataTable)accessdb.ExecuteSP(strpdmConnection, "sp_NNLFGNoShuDaiAPS", common.Choose.RetOneRecord, new object[] { "", "", "", "", "", "" });

            //8.其它模具(其它设备模制具)
            DataTable dtDetail8 = new DataTable("dtDetail8");
            dtDetail8 = (DataTable)accessdb.ExecuteSP(strpdmConnection, "sp_NNLFGNoOtherModuleAPS", common.Choose.RetOneRecord, new object[] { "", "", "", "", "", "" });
            dtDetail1.Clear();
            dtDetail2.Clear();
            dtDetail3.Clear();
            dtDetail4.Clear();
            dtDetail5.Clear();
            dtDetail6.Clear();
            dtDetail7.Clear();
            dtDetail8.Clear();
            

            //9.包装
            string strSQL = "Select NNL成品号  NNLFGNo,客户 CustCode ,料号 PartDetail, 图纸版本 DrawVersion,"
                           + " cast('' as nvarchar(20)) MoNo, *,外箱编码 + '(' + 外箱规格 + ')' 外箱编码及规格,"
                           + " 胶袋编码 + '(' + 胶袋规格 + ')' 胶袋编码及规格, "
                           + " UL标签编码 + '(' + UL标签规格 + ')' UL标签编码及规格  "
                           + " from qryNNLFGNoPacking WHERE 1=2";
            DataTable dtDetail9 = new DataTable("dtDetail9");
            dtDetail9 = accessdb.GetRecord(strpdmConnection, strSQL, null).ADODataRst;

            dtDetail9.Clear();

            //2013-07-18取得工程师数据和审核数据
            string strList = "SELECT * FROM  \n"
                           + "(SELECT bb.NNL成品号,bb.客户,bb.料号, bb.图纸版本,bb.审核人,bb.工程师 FROM  qryNNLFGNoInfo bb \n"
                           + "INNER JOIN  \n"
                           + "--找到最大的料号对应的图纸版本，以数字开头，并且审核人不能为空 \n"
                           + "(SELECT qni.NNL成品号,qni.客户,qni.料号,max(图纸版本) 图纸版本  \n"
                           + "FROM qryNNLFGNoInfo qni \n"
                           + "WHERE LEFT(图纸版本,1) in ('1','2','3','4','5','6','7','8','9','0') \n"
                           + "AND isnull(审核人,'')<>'' \n"
                           + "GROUP BY qni.NNL成品号,qni.客户,qni.料号) aa \n"
                           + "ON   aa.NNL成品号=bb.NNL成品号  \n"
                           + "AND  aa.客户=bb.客户  \n"
                           + "AND  aa.料号=bb.料号  \n"
                           + "AND  aa.图纸版本=bb.图纸版本) cc";
            DataTable dtProInf = accessdb.GetRecord(strpdmConnection, strList, null).ADODataRst;


            //找到所选择的每一笔数据,写入到相应的表格中
            for (int row = 0; row < drs.Length; row++)
            {                
                //PDM中的料号是取APS料号中的前9位
                string NNLFGNo = drs[row]["ItemCode"].ToString();
                NNLFGNo = NNLFGNo.Substring(0, 9);

                string CustCode = drs[row]["CustomerCode"].ToString().Replace("\r", "").Replace("\n", ""); ;
                string PartDetail = drs[row]["Spec1Code"].ToString();
                PartDetail = PartDetail.Replace("\r", "").Replace("\n","");
                //取制令单号
                string MoNo = drs[row]["Code"].ToString();

                ////取APS中的视图中的BOM版本号最后面的三位数，传至PDM中的存储过程
                //string DrawVersion = drs[row]["OrderUser_UBOM"].ToString();
                //DrawVersion = DrawVersion.Split('>')[1];

                //2013-08-06改以为料号，成品号，客户取数，取最大图纸版本的数据


                string DrawVersion = "";
                string strChecker = "";
                string strEngineer = "";
                DataRow[] drList = dtProInf.Select("客户='" + CustCode
                                                     + "' and NNL成品号='" + NNLFGNo
                                                     + "' and 料号='" + PartDetail +"'");
               if (drList.Length >= 1) 
               {
                   //取得审核人
                   strChecker=drList[0]["审核人"].ToString();

                   //取得工程师
                   strEngineer = drList[0]["工程师"].ToString();

                   //取得图纸号
                   DrawVersion = drList[0]["图纸版本"].ToString();
                }


               //NNLFGNo = "asd";
               //CustCode = "aaaa";
               //PartDetail = "bbbb";
               //DrawVersion = "af";
               //strChecker = "checker";
               //strEngineer = "engineer";
               ////加入主表数据
               //dtMaster.Rows.Add(new object[] {NNLFGNo,  //NNL料号
               //                                  CustCode, //客户
               //                                  PartDetail,   //客户料号
               //                                  DrawVersion,
               //                                  MoNo,
               //                                  strChecker,
               //                                  strEngineer });  //图纸编号

               //NNLFGNo = "asd1";
               //CustCode = "aaaa";
               //PartDetail = "bbbb";
               //DrawVersion = "af";
               //strChecker = "checker1";
               //strEngineer = "engineer1";

                //加入主表数据
                dtMaster.Rows.Add(new object[] {NNLFGNo,  //NNL料号
                                                 CustCode, //客户
                                                 PartDetail,   //客户料号
                                                 DrawVersion,
                                                 MoNo,
                                                 strChecker,
                                                 strEngineer });  //图纸编号
              
                //运行PDM系统提供的存储过程,写入到各明细表中
                //1.端子铆压(端子与电线或其他物料间的铆压)
                DataTable dtDetail1Tmp = new DataTable("dtDetail1Tmp");
                dtDetail1Tmp = (DataTable)accessdb.ExecuteSP(strpdmConnection,
                    "sp_NNLFGNoDZDXMaoYaAPS",
                    common.Choose.RetOneRecord, new object[] { NNLFGNo, CustCode, PartDetail, DrawVersion, "", MoNo });
                if(dtDetail1Tmp.Rows.Count>=1)
                {
                    for (int i = 0; i < dtDetail1Tmp.Rows.Count; i++)
                    {
                        dtDetail1.Rows.Add(dtDetail1Tmp.Rows[i].ItemArray);

                       
                    }
                }

                ////以下为测试数据
                //for (int i = 0; i < 6; i++)
                //{
                //    string remark = "";
                //    if (i % 2 == 0)
                //    {
                //        remark = "第" + (i + 1).ToString() + "笔记录,有备注,要显示出来!";
                //    }
                //    dtDetail1.Rows.Add(new object[] {NNLFGNo+ i.ToString(), DrawVersion,"sdfsdd",
                //        PartDetail,  "asfdfw","","","","","","","","","","rrr","rtr","rt","rr","模具储位叼","trt","rtr","rtrtrt","","ttrrr",remark,
                //        NNLFGNo, CustCode, PartDetail, DrawVersion, MoNo });

                //}

                //2.电线印字
                DataTable dtDetail2Tmp = new DataTable("dtDetail2Tmp");
                dtDetail2Tmp = (DataTable)accessdb.ExecuteSP(strpdmConnection,
                    "sp_NNLFGNoDXYinZhiaps", common.Choose.RetOneRecord,
                    new object[] { NNLFGNo, CustCode, PartDetail, DrawVersion, "", MoNo });
                if (dtDetail2Tmp.Rows.Count >= 1)
                {
                    for (int i = 0; i < dtDetail2Tmp.Rows.Count; i++)
                    {
                        dtDetail2.Rows.Add(dtDetail2Tmp.Rows[i].ItemArray);
                    }
                }

                //3.半成品电测（电性测试）
                DataTable dtDetail3Tmp = new DataTable("dtDetail3Tmp");
                dtDetail3Tmp = (DataTable)accessdb.ExecuteSP(strpdmConnection,
                    "sp_NNLFGNoDianCheAPS", common.Choose.RetOneRecord,
                    new object[] { NNLFGNo, CustCode, PartDetail, DrawVersion, "",  MoNo });

                if (dtDetail3Tmp.Rows.Count >= 1)
                {
                    for (int i = 0; i < dtDetail3Tmp.Rows.Count; i++)
                    {
                        dtDetail3.Rows.Add(dtDetail3Tmp.Rows[i].ItemArray);
                    }
                }

                //4.端子插拔 
                DataTable dtDetail4Tmp = new DataTable("dtDetail4Tmp");
                dtDetail4Tmp = (DataTable)accessdb.ExecuteSP(strpdmConnection,
                    "sp_NNLFGNoDZChaBaAPS",
                    common.Choose.RetOneRecord, new object[] { NNLFGNo, CustCode, PartDetail, DrawVersion, "", MoNo });

                if (dtDetail4Tmp.Rows.Count >= 1)
                {
                    for (int i = 0; i < dtDetail4Tmp.Rows.Count; i++)
                    {
                        dtDetail4.Rows.Add(dtDetail4Tmp.Rows[i].ItemArray);
                    }
                }

                //5.IDC(刺破型端子铆压要求)
                DataTable dtDetail5Tmp = (DataTable)accessdb.ExecuteSP(strpdmConnection,
                    "sp_NNLFGNoIDCAPS",
                    common.Choose.RetOneRecord, new object[] { NNLFGNo, CustCode, PartDetail, DrawVersion, "", MoNo });

                if (dtDetail5Tmp.Rows.Count >= 1)
                {
                    for (int i = 0; i < dtDetail5Tmp.Rows.Count; i++)
                    {
                        dtDetail5.Rows.Add(dtDetail5Tmp.Rows[i].ItemArray);
                    }
                }


                //6.P架保持力(端子与P架)
                DataTable dtDetail6Tmp = (DataTable)accessdb.ExecuteSP(strpdmConnection,
                    "sp_NNLFGNoDZPJia_BaoChiLiAPS",
                    common.Choose.RetOneRecord, new object[] { NNLFGNo, CustCode, PartDetail, DrawVersion, "","", MoNo });

                if (dtDetail6Tmp.Rows.Count >= 1)
                {
                    for (int i = 0; i < dtDetail6Tmp.Rows.Count; i++)
                    {
                        dtDetail6.Rows.Add(dtDetail6Tmp.Rows[i].ItemArray);
                    }
                }

                //7.束带(束带绷张力)
                DataTable dtDetail7Tmp = (DataTable)accessdb.ExecuteSP(strpdmConnection,
                    "sp_NNLFGNoShuDaiAPS",
                    common.Choose.RetOneRecord, new object[] { NNLFGNo, CustCode, PartDetail, DrawVersion, "", MoNo });


                if (dtDetail7Tmp.Rows.Count >= 1)
                {
                    for (int i = 0; i < dtDetail7Tmp.Rows.Count; i++)
                    {
                        dtDetail7.Rows.Add(dtDetail7Tmp.Rows[i].ItemArray);
                    }
                }

                /////*以下为测试数据
                //for (int i = 0; i < 15; i++)
                //{
                //    dtDetail7.Rows.Add(new object[] { "asd44f" + i.ToString(), "sd2342434", "deerert", "", "", "", "", NNLFGNo, CustCode, PartDetail, DrawVersion, MoNo });
                //}
                 
                 //*/

                //8.其它模具(其它设备模制具)
                DataTable dtDetail8Tmp = (DataTable)accessdb.ExecuteSP(strpdmConnection,
                    "sp_NNLFGNoOtherModuleAPS",
                    common.Choose.RetOneRecord, new object[] { NNLFGNo, CustCode, PartDetail, DrawVersion, "", MoNo });
                if (dtDetail8Tmp.Rows.Count >= 1)
                {
                    for (int i = 0; i < dtDetail8Tmp.Rows.Count; i++)
                    {
                        dtDetail8.Rows.Add(dtDetail8Tmp.Rows[i].ItemArray);
                    }
                }
                ///////*
                //for (int i = 0; i < 20; i++)
                //{
                //    dtDetail8.Rows.Add(new object[] { "asdf" + i.ToString(), "sd", "sdf", NNLFGNo, CustCode, PartDetail, DrawVersion, MoNo });
                //}

                //for (int i = 0; i < 3; i++)
                //{
                //    dtDetail8.Rows.Add(new object[] { "asdf1" + i.ToString(), "sd", "sdf", NNLFGNo, CustCode, PartDetail, DrawVersion, MoNo });
                //} 
                //////以上为测试数据*/

                //9.包装
                strSQL = "Select top 1 NNL成品号  NNLFGNo,客户 CustCode ,料号 PartDetail, 图纸版本 DrawVersion,"
                        + "'" + MoNo + "' MoNo , * ,外箱编码 + '(' + 外箱规格 + ')' 外箱编码及规格,"
                        + "  胶袋编码 + '(' + 胶袋规格 + ')' 胶袋编码及规格, "
                        + "  UL标签编码 + '(' + UL标签规格 + ')' UL标签编码及规格  from qryNNLFGNoPacking "
                        + "  WHERE  Not 审核人 is null "
                        + "  And    NNL成品号='" + NNLFGNo
                        + "' And    图纸版本='" + DrawVersion
                        + "' And    客户='" + CustCode
                        + "' And    料号='" + PartDetail + "'";

                strSQL = "Select top 1 " + " '" + NNLFGNo + "'  NNLFGNo,'CM02' CustCode ,'裁断外发金准加工' PartDetail," + "'"
                        + DrawVersion + "' DrawVersion,"
                        + "'" + MoNo + "' MoNo , * ,外箱编码 + '(' + 外箱规格 + ')' 外箱编码及规格,"
                        + " 胶袋编码 + '(' + 胶袋规格 + ')' 胶袋编码及规格, "
                        + " UL标签编码 + '(' + UL标签规格 + ')' UL标签编码及规格 from qryNNLFGNoPacking ";
                //////+ " WHERE  Not 审核人 is null "
                //+ " And NNL成品号='" + NNLFGNo
                //+ "' And 图纸版本='" + DrawVersion + "'";
                DataTable dtDetail9Tmp = accessdb.GetRecord(strpdmConnection, strSQL, null).ADODataRst;

                dtDetail9Tmp.Rows[0]["SingleChengPic"] = @"c:\test.jpg";
                dtDetail9Tmp.Rows[0]["SinglePackPic"] = @"c:\test.jpg";

                if (dtDetail9Tmp.Rows.Count >= 1)
                {
                    for (int i = 0; i < dtDetail9Tmp.Rows.Count; i++)
                    {
                        dtDetail9.Rows.Add(dtDetail9Tmp.Rows[i].ItemArray);

                    }
                }

            }


            //writer.Close();
            //tempStream.Close();

            DevExpress.XtraReports.UI.XtraReport report = new DevExpress.XtraReports.UI.XtraReport();

            report = new rptProductInf(dtMaster,dtDetail1,dtDetail2,dtDetail3,
                                       dtDetail4,dtDetail5,dtDetail6,dtDetail7,
                                       dtDetail8,dtDetail9);

            //report = new rptProcessCard();
            report.Parameters["title"].Value = "成  品  料  号  信  息";

            //报表相关参数设定
            report.Parameters["username"].Value = common._username;

            //批次号
            report.Parameters["TranNo"].Value = this.lokPlanNo.Text;
            report.ShowPreview();
        }

        private void ShowReport()
        {

            string strSQL = "SELECT * FROM vie_ProcessCard" + DeptNo + " where itemid='" + ItemID + "'";
            DataTable dtReport =accessdb.GetRecord(strSQL).ADODataRst;

            DevExpress.XtraReports.UI.XtraReport report = new DevExpress.XtraReports.UI.XtraReport();

            report = new rptProcessCard();
            report.Parameters["title"].Value = "制 程 识 别 卡";


            //报表相关参数设定
            report.Parameters["username"].Value = common._username;

            //报表显示
            ReportShow.ShowReport(report, true, dtReport);

           

        }

        private void PrintReport()
        {

            string strSQL = "SELECT * FROM vie_ProcessCard" + DeptNo + " where itemid='" + ItemID + "'";
            DataTable dtReport = accessdb.GetRecord(strSQL).ADODataRst;

            DevExpress.XtraReports.UI.XtraReport report = new DevExpress.XtraReports.UI.XtraReport();

            report = new rptProcessCard();
            report.PrintingSystem.ShowMarginsWarning = false;

            report.Parameters["title"].Value = "制 程 识 别 卡";


            //报表相关参数设定
            report.Parameters["username"].Value = common._username;

            //报表显示
           if(! ReportShow.ShowReport(report, false, dtReport)) return;

            //如果打印成功，则需要更新打印的次数
           strSQL = "exec pro_UpdatePrintCount" + DeptNo + " '" + ItemID + "'";
           accessdb.RsChange(strSQL);

        }

        private bool subInsertData()
        {
            if (!common.CheckExistsData(this.ListView)) return false;
            this.ListView.CloseEditor();
            this.ListView.UpdateCurrentRow();
            DataTable viewt = (DataTable)this.ListGrid.DataSource;
            DataRow[] drs = viewt.Select("chkSelect=1");
            if (drs.Length < 1)
            {
                DevExpress.XtraEditors.XtraMessageBox.Show("请至少选择一笔数据!", common.sysParameter.MessageInf, MessageBoxButtons.OK, MessageBoxIcon.Information);
                return false;
            }

            //取出自动机判断制令量的数据     
            double projectUA = Convert.ToDouble(common.GetLanguageWord("PropertyID", "ProjectUser_UA"));

            //取出电脑机选择条件制令量
            double ProjectUser_UQTY = Convert.ToDouble(common.GetLanguageWord("PropertyID",  "ProjectUser_UQTY"));

            //取出电脑机选择条件制令量
            double ProjectUser_Price = Convert.ToDouble(common.GetLanguageWord("PropertyID", "ProjectUser_Price"));

            string tranNo = this.lokPlanNo.Text;
            ItemID = accessdb.GetField("SELECT CONVERT(VARCHAR(25),GETDATE(),121)").ToString();
            string strSqlInsert = " set xact_abort on begin tran "
                                    + "  insert into ProcessCardItem" + DeptNo
                                    + " select '" + tranNo + "',"
                                    + "code,getdate(),'" + ItemID + "'"
                                    + " from OrdersOut" + DeptNo + " where code in(";
            string stritemid = "";
            for (int row = 0; row < drs.Length; row++)
            {
                stritemid += "'" +  drs[row]["code"].ToString() + "',";
            }
            stritemid = stritemid.Substring(0, stritemid.Length - 1);
            strSqlInsert += stritemid + ")      ";

            strSqlInsert += " and tranno='" + tranNo + "'\n"
                           + " commit tran";
            if (!accessdb.RsChange(strSqlInsert)) return false;
            strSqlInsert = " EXEC pro_ProcessCard" + DeptNo + "\r\n"
                           + " @tranno ='" + tranNo + "', "
                           + " @ItemID ='" + ItemID + "', "
                           + " @ProjectUA = " + projectUA.ToString() + ",\r\n"
                           + " @ProjectUser_UQTY = " + ProjectUser_UQTY.ToString() + ",\r\n"
                           + " @projectUser_Uprice = " + ProjectUser_Price.ToString() + "\r\n";
            if (!accessdb.RsChange(strSqlInsert)) return false;
            return true;
        }
            
        private void subPrintReport()
        {
            DataTable dtSel = ((DataView)ListView.DataSource).Table;
            if (dtSel.Rows.Count <= 0)
            {
                DevExpress.XtraEditors.XtraMessageBox.Show("没有数据可供打印!", common.sysParameter.MessageInf, MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;

            }

            DevExpress.XtraReports.UI.XtraReport report=new rptProcessCard();
           
            //报表相关参数设定
            report.Parameters["username"].Value = common._username;
            report.Parameters["title"].Value = common.sysParameter.ReportTitleZ1;
           
            //报表显示
            ReportShow.ShowReport(report, true, dtOrder);
          
        }


        private bool CheckData()
        {
            if (this.lokPlanNo.Text == "")
            {
                DevExpress.XtraEditors.XtraMessageBox.Show("生产计划版本号不能为空，请检查!", common.sysParameter.MessageInf, MessageBoxButtons.OK, MessageBoxIcon.Information);
                this.lokPlanNo.Focus();
                return false;
            }


            if (this.lokDepart.Text == "" )  
            {
                DevExpress.XtraEditors.XtraMessageBox.Show("最终部门不能为空，请检查!", common.sysParameter.MessageInf, MessageBoxButtons.OK, MessageBoxIcon.Information);
                this.lokDepart.Focus();
                return false;
            }



            return true;
        }



        private void subPrint()
        {
            if (!common.CheckExistsData(this.ListView)) return;
            common.PrintView(this.ListGrid, "计划数据");
        }

        private void subExportXLS()
        {
            try
            {
                if (!common.CheckExistsData(this.ListView)) return;
                common.ExportExcel(this.ListView);
                return;
            }
            catch (Exception ex)
            {
                DevExpress.XtraEditors.XtraMessageBox.Show(ex.Message, common.sysParameter.MessageInf, MessageBoxButtons.OK, MessageBoxIcon.Information);
            }

        }

        private void SearchData()
        {
            Cursor currentCursor = Cursor.Current;

            Cursor.Current = Cursors.WaitCursor;

            DeptNo = this.lokDepart.Text;
            if (DeptNo == "Z2")
                DeptNo = "Z1";

            //取得路径
            string filePath = common.GetLanguageWord("PropertyID", "ProjectUser_UDfolder").ToString();

            //根据选择的条件进行报表显示
            string strSQL = "select cast(0 as bit) as chkSelect ,  Code, ItemCode, dbo.GetShortDate( EST) est,"
                           + " dbo.GetShortDate( LET) let, Qty,  dbo.GetShortDate(starttime) starttime,"
                           + " dbo.GetShortDate(endtime) endtime,Spec1Code,CustomerCode,1 as showTZ,Spec2Code,bb.PrintCount,"  
                           //取得图片文件的名称
                           + "'" + filePath + "' + '\\'  + CustomerCode + '\\' +  REPLACE( replace(rtrim(Spec1Code),CHAR(13),''),CHAR(10),'') + '.pdf' as picPath,"
                            //2012-04-05显示订单的ChildCode字段中的第一个工序的资源代码，如果存在为空的资源，可能是工作没有导出来，导致找不到相关的工作
                           + " (SELECT DISTINCT oz.OperationMainResCode "
                           + " FROM Operation" + DeptNo + "  oz WHERE oz.TranNo=aa.TranNo AND   oz.ordercode=aa.Code "
                           + " and oz.procno=left(aa.childcode,2) ) Resource, "
                           //2013-06-26加入BOM版本信息，以打印NNL品号信息
                           + " aa.OrderUser_UBOM "
                           + " FROM OrdersOut" + DeptNo
                           + " aa left outer join ProcesCardPrint" + DeptNo + " bb  on aa.code=bb.MoNo"
                           + " where TranNo='" + this.lokPlanNo.Text + "'";

            if (strStartTime != "")
            {
                strSQL += " and dbo.getshortdate( strartTime)>='" + strStartTime + "'";

            }

            if (strEndTime != "")
            {
                strSQL += " and  dbo.getshortdate(strartTime)<='" + strEndTime + "'";

            }

            if (this.lokDepart.Text!="")
            {
                if (this.lokDepart.Text=="Z2")
                {
                    strSQL += " and  Spec2Code like '%2%' ";
                }
                else
                {
                    strSQL += " and  Spec2Code like '%" + this.lokDepart.Text.Substring(1, 1) + "%' and  Spec2Code not like '%2%'";
                }
            }
           
            dtOrder = accessdb.GetRecord(strSQL).ADODataRst;
            common.SubShowList(dtOrder, this.ListGrid, this.ListView, false);
            common.subIniGrid(this.ListView, common.enumGridStyle.ViewStyle);
            this.ListView.Columns[0].OptionsColumn.AllowEdit = true;
            this.ListView.Columns[0].OptionsColumn.AllowFocus = true;
            ListView.Columns[0].OptionsColumn.ReadOnly = false;
            this.ListGrid.Tag = 0;
            Cursor.Current = currentCursor;
 
        }



        #endregion

        //切换用户
        private void txtChange_Click(object sender, EventArgs e)
        {
           
             IniDataSource();
           

        }

        private void frmProcessCard_FormClosing(object sender, FormClosingEventArgs e)
        {
            common._its_accessdb = null;
            GC.Collect();
        }
    }
}
